const logger = require('./Logger');
const accessTokenDao = require('../daos/AccessTokenDao');
const {appid, appsecret} = require('../../resources/WechatConfig').development.config;
const API = require('co-wechat-api');

Date.prototype.format = function (format) {
    let o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(), //day
        "H+": this.getHours(), //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
        "S": this.getMilliseconds() //millisecond
    };
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1,
            (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (let k in o)
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1,
                RegExp.$1.length == 1 ? o[k] :
                    ("00" + o[k]).substr(("" + o[k]).length));
        }
    return format;
};
//  向微信服务端请求获取 token 并保存数据库
let api = new API(appid, appsecret, async function () {
    let accessToken = await accessTokenDao.find();
    return accessToken;
}, async function (token) {
    try {
        await accessTokenDao.save(token);
    } catch (e) {
        logger.error('AccessToken 更新数据库失败',+e);
    }

});
module.exports = api;